package com.jieao.template.config.shiroConfig;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class CustomSessionManager extends DefaultWebSessionManager
{
    private static final String AUTHORIZATION = "authorization";

    public CustomSessionManager()
    {
        super();
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response)
    {
        String sessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        if (sessionId != null)
        {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        }
        else
        {
            return super.getSessionId(request, response);
        }

//        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
//        String sessionId = httpServletRequest.getHeader(AUTHORIZATION);
//        if (sessionId == null)
//        {
//            Cookie[] cookies = httpServletRequest.getCookies();
//            LinkedList<String> cookieList = new LinkedList<>();
//            if (cookies != null)
//            {
//                for (Cookie cookie : cookies)
//                {
//                    System.err.println(cookie.getPath());
//                    if ("JSESSIONID".equals(cookie.getName()))
//                    {
//                        cookieList.add(cookie.getValue());
//                    }
//                }
//                if (cookieList.size() > 1)
//                {
//                    sessionId = cookieList.get(1);
//                }
//                else
//                {
//                    sessionId = cookieList.get(0);
//                }
//            }
//            else
//            {
//                return super.getSessionId(request, response);
//            }
//        }
//        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
//                ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
//        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
//        request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
//        return sessionId;
    }


}
